package com.uduemc.biso.node.module.controller;

import com.github.pagehelper.PageInfo;
import com.uduemc.biso.core.utils.RestResult;
import com.uduemc.biso.node.core.entities.HDomain;
import com.uduemc.biso.node.core.node.extities.DomainRedirectList;
import com.uduemc.biso.node.module.service.HDomainService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/h-domain")
public class HDomainController {

	private static final Logger logger = LoggerFactory.getLogger(HDomainController.class);

	@Autowired
	private HDomainService hDomainServiceImpl;

	@GetMapping("/find-one/{id:\\d+}")
	public RestResult findOne(@PathVariable("id") Long id) {
		HDomain data = hDomainServiceImpl.findOne(id);
		if (data == null) {
			return RestResult.noData();
		}
		return RestResult.ok(data, HDomain.class.toString());
	}

	@GetMapping(value = { "/find-all" })
	public RestResult findAll(@PageableDefault(page = 0, size = 12) Pageable pageable) {
		logger.info("pageable: " + pageable.toString());
		List<HDomain> list = hDomainServiceImpl.findAll(pageable);
		return RestResult.ok(list, HDomain.class.toString(), true);
	}

	@PostMapping("/insert")
	public RestResult insert(@Valid @RequestBody HDomain domain, BindingResult errors) {
		logger.info(domain.toString());
		if (errors.hasErrors()) {
			Map<String, Object> message = new HashMap<>();
			for (FieldError fieldError : errors.getFieldErrors()) {
				String field = fieldError.getField();
				String defaultMessage = fieldError.getDefaultMessage();
				message.put(field, defaultMessage);
			}

			return RestResult.error(message);
		}
		HDomain data = hDomainServiceImpl.insert(domain);
		return RestResult.ok(data, HDomain.class.toString());
	}

	@PutMapping("/update-by-id")
	public RestResult updateById(@Valid @RequestBody HDomain domain, BindingResult errors) {
		if (errors.hasErrors()) {
			Map<String, Object> message = new HashMap<>();
			for (FieldError fieldError : errors.getFieldErrors()) {
				String field = fieldError.getField();
				String defaultMessage = fieldError.getDefaultMessage();
				message.put(field, defaultMessage);
			}

			return RestResult.error(message);
		}

		Long id = domain.getId();
		HDomain data = hDomainServiceImpl.findOne(id);
		if (data == null) {
			return RestResult.noData();
		}
		HDomain uDomain = hDomainServiceImpl.updateById(domain);
		return RestResult.ok(uDomain, HDomain.class.toString());
	}

	@PutMapping("/update-all-by-id")
	public RestResult updateAllById(@Valid @RequestBody HDomain domain, BindingResult errors) {
		if (errors.hasErrors()) {
			Map<String, Object> message = new HashMap<>();
			for (FieldError fieldError : errors.getFieldErrors()) {
				String field = fieldError.getField();
				String defaultMessage = fieldError.getDefaultMessage();
				message.put(field, defaultMessage);
			}

			return RestResult.error(message);
		}

		Long id = domain.getId();
		HDomain data = hDomainServiceImpl.findOne(id);
		if (data == null) {
			return RestResult.noData();
		}
		HDomain uDomain = hDomainServiceImpl.updateAllById(domain);
		return RestResult.ok(uDomain, HDomain.class.toString());
	}

	@GetMapping("/delete-by-id/{id:\\d+}")
	public RestResult deleteById(@PathVariable("id") Long id) {
		// 是否存在
		HDomain data = hDomainServiceImpl.findOne(id);
		// 不存在 返回 RestResult.ok();
		if (data == null) {
			return RestResult.ok();
		}
		// 存在 返回 RestResult.ok(data, Domain.class.toString());
		hDomainServiceImpl.deleteByIdAndRedirect(id);
		return RestResult.ok(data);
	}

	/**
	 * 通过 domain_name 数据库中查找对应的数据
	 * 
	 * @param domainName
	 * @return
	 */
	@PostMapping("/find-one-by-domainname")
	public RestResult findByDomainName(@RequestParam("domainName") String domainName) {
		logger.info("domainName: " + domainName);
		HDomain data = hDomainServiceImpl.findByDomainName(domainName);
		if (data == null) {
			return RestResult.noData();
		}
		return RestResult.ok(data, HDomain.class.toString());
	}

	/**
	 * 通过 host_id 查找所有的域名
	 * 
	 * @param hostid
	 * @return
	 */
	@GetMapping("/find-all-by-hostid/{hostid:\\d+}")
	public RestResult findAllByHostId(@PathVariable("hostid") Long hostid) {
		logger.info("hostid: " + hostid);
		List<HDomain> list = hDomainServiceImpl.findAllByHostId(hostid);
		return RestResult.ok(list, HDomain.class.toString(), true);
	}

	/**
	 * 通过 host_id 查找系统域名
	 * 
	 * @param hostid
	 * @return
	 */
	@GetMapping("/find-default-domain-by-hostid/{hostid:\\d+}")
	public RestResult findDefaultDomainByHostId(@PathVariable("hostid") Long hostid) {
		logger.info("hostid: " + hostid);
		HDomain data = hDomainServiceImpl.findDefaultDomainByHostId(hostid);
		if (data == null) {
			return RestResult.noData();
		}
		return RestResult.ok(data, HDomain.class.toString());
	}

	/**
	 * 通过 host_id 查找用户绑定域名
	 * 
	 * @param hostid
	 * @return
	 */
	@GetMapping("/find-user-domain-by-hostid/{hostid:\\d+}")
	public RestResult findUserDomainByHostId(@PathVariable("hostid") Long hostid) {
		logger.info("hostid: " + hostid);
		List<HDomain> list = hDomainServiceImpl.findUserDomainByHostId(hostid);
		return RestResult.ok(list, HDomain.class.toString(), true);
	}

	/**
	 * 通过 id，hostId 获取域名数据信息
	 * 
	 * @param hostId
	 * @param id
	 * @return
	 */
	@GetMapping("/find-domain-by-hostid-and-id/{id:\\d+}/{hostId:\\d+}")
	public RestResult findDomainByHostidAndId(@PathVariable("id") long id, @PathVariable("hostId") long hostId) {
		HDomain hDomain = hDomainServiceImpl.findDomainByHostidAndId(id, hostId);
		return RestResult.ok(hDomain, HDomain.class.toString());
	}

	/**
	 * 通过 hostId 获取域名重定向数据列表
	 * 
	 * @param hostId
	 * @return
	 */
	@GetMapping("/find-domain-redirect-by-host-id/{hostId:\\d+}")
	public RestResult findDomainRedirectByHostId(@PathVariable("hostId") long hostId) {
		DomainRedirectList data = hDomainServiceImpl.findDomainRedirectByHostId(hostId);
		return RestResult.ok(data, DomainRedirectList.class.toString());
	}

	/**
	 * 通过 hostId 获取绑定的域名总数
	 */
	@GetMapping("/total-binding-by-host-id/{hostId:\\d+}")
	public RestResult totalBindingByHostId(@PathVariable("hostId") long hostId) {
		if (hostId < 1) {
			return RestResult.error();
		}
		int total = hDomainServiceImpl.totalBindingByHostId(hostId);
		return RestResult.ok(total, Integer.class.toString());
	}

	/**
	 * 通过条件过滤数据
	 */
	@PostMapping("/find-page-info")
	public RestResult findPageInfo(
			// 模糊查询域名
			@RequestParam("domainName") String domainName,
			// 过滤 hostId 的部分
			@RequestParam("hostId") long hostId,
			// 过滤 domainType 的部分
			@RequestParam("domainType") short domainType,
			// 过滤 status 域名的状态部分
			@RequestParam("status") short status,
			// 排序方式 1-顺序 2-倒序
			@RequestParam("orderBy") short orderBy,
			// 分页当前页
			@RequestParam("page") int page,
			// 分页的步长
			@RequestParam("pageSize") int pageSize) {

		PageInfo<HDomain> data = hDomainServiceImpl.findPageInfo(domainName, hostId, domainType, status, orderBy, page, pageSize);

		return RestResult.ok(data, PageInfo.class.toString());
	}

	/**
	 * 通过条件获取到 HDomain 的 List 数据
	 * 
	 * @param minId
	 * @param domainType
	 * @param status
	 * @param orderBy
	 * @param page
	 * @param pageSize
	 * @return
	 */
	@PostMapping("/find-by-where")
	public RestResult findByWhere(
			// 开始查询的ID
			@RequestParam("minId") long minId,
			// 过滤 domainType 的部分
			@RequestParam("domainType") short domainType,
			// 过滤 status 的部分
			@RequestParam("status") short status,
			// 排序方式 1-顺序 2-倒序
			@RequestParam("orderBy") int orderBy,
			// 分页当前页
			@RequestParam("page") int page,
			// 分页的步长
			@RequestParam("pageSize") int pageSize) {

		List<HDomain> data = hDomainServiceImpl.findByWhere(minId, domainType, status, orderBy, page, pageSize);

		return RestResult.ok(data, List.class.toString(), true);
	}

	/**
	 * 通过条件获取到 HDomain 的 List 数据
	 * 
	 * @param hostId
	 * @param domainType
	 * @param status
	 * @param orderBy
	 * @return
	 */
	@PostMapping("/find-by-host-id-domain-type-status")
	public RestResult findByHostIdDomainTypeStatus(
			// 开始查询的ID
			@RequestParam("hostId") long hostId,
			// 过滤 domainType 的部分
			@RequestParam("domainType") short domainType,
			// 过滤 status 的部分
			@RequestParam("status") short status,
			// 排序方式 1-顺序 2-倒序
			@RequestParam("orderBy") int orderBy) {

		List<HDomain> data = hDomainServiceImpl.findByHostIdDomainTypeStatus(hostId, domainType, status, orderBy);

		return RestResult.ok(data, List.class.toString(), true);
	}

	/**
	 * 域名重定向使用数量统计
	 * 
	 * @param trial 是否试用 -1:不区分 0:试用 1:正式
	 * @param review 制作审核 -1:不区分 0-未审核 1-审核通过 2-审核不通过
	 * @return
	 */
	@GetMapping("/query-domain-redirect-count/{trial:-?\\d+}/{review:-?\\d+}")
	public RestResult queryDomainRedirectCount(@PathVariable("trial") int trial, @PathVariable("review") int review) {
		Integer count = hDomainServiceImpl.queryDomainRedirectCount(trial, review);
		return RestResult.ok(count, Integer.class.toString());
	}
}
